package xyz.liut.ee.api

import jakarta.servlet.annotation.MultipartConfig
import jakarta.servlet.annotation.WebServlet
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import xyz.liut.ee.req.getHost
import xyz.liut.ee.req.getSimpleReqInfo
import xyz.liut.ee.resp.ResponseEntity
import xyz.liut.ee.web.BaseNoDefaultServlet
import xyz.liut.ee.web.gson
import xyz.liut.logcat.kt.logDebug


/**
 * relocation test
 */
@WebServlet("/redirect")
@MultipartConfig
class Redirect : BaseNoDefaultServlet() {

    override fun service(req: HttpServletRequest, resp: HttpServletResponse) {
        super.service(req, resp)

        val code: Int = req.getParameter("code")?.toIntOrNull() ?: 302

        val defLocation = if (req.queryString.isNullOrEmpty()) "${req.getHost()}/echo"
        else "${req.getHost()}/echo?${req.queryString}"

        val location: String = req.getParameter("location") ?: defLocation

        val reqInfo = req.getSimpleReqInfo()

        val respBean = ResponseEntity(
            msg = "回响",
            code = code,
            data = reqInfo
        )

        val msg: String = gson.toJson(respBean)

        resp.contentType = "application/json;charset=UTF-8"
        resp.characterEncoding = "UTF-8"
        resp.status = code
        resp.setHeader("location", location)
        resp.writer.println(msg)
        logDebug { msg }

    }

}
